/*
 * 人人信用管理有限公司版权所有.
 * 
 * @Description:
 * 
 * @author: liyuliang
 * 
 * @date: 20 Apr 2017 10:44:16 am
 * 
 * 注意：本内容仅限于人人信用管理有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 */

package com.rrx360.common.web;

import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.rrx360.common.context.ActionContext;
import com.rrx360.common.web.enums.PageTemplateType;
import com.rrx360.common.web.spring.RxCustomDateEditor;
import com.rrx360.common.web.util.WebUtil;

public class BaseController implements ServletContextAware {

  protected Logger logger = LogManager.getLogger();

  private ServletContext servletContext;

  public void setServletContext(ServletContext servletContext) {
    this.servletContext = servletContext;
  }

  public HttpServletRequest getRequest() {
    return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  }

  public HttpServletResponse getResponse() {
    return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
  }

  public ServletContext getServletContext() {
    return servletContext;
  }

  @InitBinder
  protected void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Date.class, new RxCustomDateEditor(true));
    binder.registerCustomEditor(java.sql.Date.class,
        new RxCustomDateEditor(java.sql.Date.class, true));
    binder.registerCustomEditor(Timestamp.class, new RxCustomDateEditor(Timestamp.class, true));
  }

  public String forward(String path) {
    return "forward:" + path;
  }

  public String page(String path) {
    if (path == null) {
      return null;
    }
    if (path.startsWith("/pc/") || path.startsWith("pc/")) {
      ActionContext.put(PageTemplateType.class, PageTemplateType.PC);
    } else if (path.startsWith("/mobile/") || path.startsWith("mobile/")) {
      ActionContext.put(PageTemplateType.class, PageTemplateType.MOBILE);
    }
    return path;
  }

  public String redirect(String path) {
    if (path != null && path.startsWith("http")) {
      return "redirect:" + path;
    }
    if (path != null && !path.startsWith("/")) {
      path = "/" + path;
    }

    String rootPath = WebUtil.getRootPath();

    return "redirect:" + rootPath + path;
  }



}
